<template>
  <div class="progress"
  @click.stop.prevent='progressClick'
  @touchstart.stop.prevent='progressTouchStart'
  @touchmove.stop.prevent='progressTouchMove'
  @touchend.stop='progressTouchEnd'
  ref='bar'>
    <div class="gone-time" ref='time'>
    </div>
    <div class="ball" ref='ball'></div>
  </div>
</template>
<script>
  const BALLWIDTH = 16;
  export default {
    name: 'progress-bar',
    props: {
      percent: {
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        touches: {},
      };
    },
    watch: {
      percent(now) {
        // 拖动和自动播放 重复处理
        if (this.touches.moving) {
          return;
        }
        const bar = this.doms.bar;
        this._offset(now * bar.offsetWidth);
      },
    },
    methods: {
      progressTouchStart() {
        this.touches.moving = true;
      },
      progressTouchMove(e) {
        this.touches.moveX = this._getDelta(e.touches[0].pageX);
        const moveX = Math.max(0, this.touches.moveX);
        this._offset(moveX);
      },
      progressTouchEnd() {
        this.touches.moving = false;
        this._triggerPercent(this.touches.moveX);
      },
      progressClick(e) {
        const delta = this._getDelta(e.pageX);
        this._offset(delta);
        this._triggerPercent(delta);
      },
      _getDelta(disX) {
        // 获取当前time的实际width
        const rect = this.doms.bar.getBoundingClientRect();
        const offsetWidth = disX - rect.left;
        return offsetWidth;
      },
      _offset(offsetWidth) {
        // 封装ball和time的移动
        const width = Math.min(offsetWidth, this.doms.bar.offsetWidth);
        this.doms.timebar.style.width = `${width}px`;
        this.doms.ball.style.transform = `translate3d(${width - BALLWIDTH / 2}px,0,0)`;
      },
      _triggerPercent(offsetWidth) {
        // 不要在子组件中改变自己的props
        const percent = offsetWidth / this.doms.bar.offsetWidth;
        this.$emit('percentChange', percent);
      },
    },
    mounted() {
      this.doms = {
        bar: this.$refs.bar,
        timebar: this.$refs.time,
        ball: this.$refs.ball,
      };
    },
  };
</script>
<style lang='stylus' scoped>
@import '~styl/var'
  .progress
    background rgba(0,0,0,.3)
    height 4px
    display inline-block
    width 100%
    .gone-time
      background $color-theme
      height 4px
    .ball
      position absolute
      box-sizing border-box
      left 0
      top 7px
      width 16px
      height 16px
      border 3px solid $color-text
      background $color-theme
      border-radius 50%
</style>
